;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require("base");
	var dialog = require("dialog");
	var leftMenu = require("../leftMenu/leftMenu");
	var topMenu = require("../topMenu/topMenu");
	var router = require("../hash/pageRouter");
	var footer = require("../footer/footer_main");
	var validate = require("validate");
	var html_delete = require("../commodityCategoryManage/commodityCategory_delete.html");
	var html_detail = require("../commodityCategoryManage/commodityCategory_detail.html");
	var html_add = require("../commodityCategoryManage/commodityCategory_add.html");
	var i = 1;
	var firstVisited = 0;
	var pageIndex = 1,
		pageSize = 10,
		totalPageCount = 1,
		totalRecordCount = 0; //分页初始化
	var imgSrc;
	var commodityCategoryIdDic = {
		enabled: 0,
		commodityCategoryId: 0
	};

	var init = function(num) {
		firstVisited = base.getUrlParam("firstVisited");
		footer.init();
		$("#footer").removeClass("none");

		leftMenu.init(num);
		topMenu.init(3);
		$("#project").removeClass("topMenu_selected");
		$(".footer").removeClass("none");
		inquireCommodityCategoryList();
		initEvent();
		router.init();
		
		if(firstVisited != 1){
			$(".table-section").removeClass("none");
		}
	};

	var initEvent = function() {

		//若未登录，则返回登陆页面
		if (base.getData("sid") == null || base.getData("sid") == "" || base.getData("sid") == undefined) {
			top.location.href = "../login/login.html";
		}

		$("#commodityCategoryBody").on("click", ".table_delete_btn", function() {
			$("#popdialog").html(html_delete);
			var $this = $(this).parents("tr.tr_style");
			var commodityCategoryIds = [];
			commodityCategoryIds.push($this.attr("commodityCategoryId"));
			deletead(commodityCategoryIds);
		});

		$("#commodityCategoryBody").on("click", ".table_details_link", function() {
			$("#popdialog").html(html_detail);
			dialog.showDialog($("#detail_category_dialog"));
			var commodityCategoryId = $(this).parent().parent().attr("commodityCategoryId");
			inquireCommodityCategoryDetail(commodityCategoryId);
			$("#bulkstockCategoryId").val(commodityCategoryId);
			$("#detail_category_dialog").on("click", ".add_material", function() {
				addMaterials();
			});
			$("#detail_category_dialog").on("click", ".delete", function() {
				$(this).parent().parent().remove();
			});
			
			$("#detail_category_dialog").on("click", ".dialogHandlerBtn", function() {
				updateMaterialTemplate();
			});
		});

		$("#bulkstockCategotyAdd").on("click", function() {
			$("#popdialog").html(html_add);
			dialog.showDialog($("#add_category_dialog"));
			$(".add_material").unbind("click").click(function(){
				addMaterials();
			});
			$("#add_category_dialog").on("click", ".delete", function() {
				$(this).parent().parent().remove();
			});
			$("#add_category_dialog").on("click", ".dialogHandlerBtn", function() {
				createBulkstockCategory();
			});
		});
		
		//搜索按钮
		$(".table-search-button-1").on("click", function() {
			pageIndex = 1;
			pageSize = 10;
			totalPageCount = 1;
			totalRecordCount = 0; //分页初始化
			ifblank();
			inquireCommodityCategoryList();
		});

		//同步按钮
		$(".table-search-button-2").on("click", function() {
			dialog.showConfirmDialog("商品类别同步", "是否确定进行同步？", function(){
				syncBulkstockCategory();
			});
		});

		$("#main").on("click", "#commodityPriceChecked", function() {
			router.route("commodityPriceManage/commodityPriceChecked.html");
		});

		$("#main").on("click", "#commodityPriceUnchecked", function() {
			router.route("commodityPriceManage/commodityPriceUnchecked.html");
		});
	};
	
	//更新
	var updateMaterialTemplate = function() {
		var bulkstockCategoryId = $("#bulkstockCategoryId").val();
		var templateName = [];
		var checkedRequired = [];
		var templateId = []
		var materials = $(".materials");
		var categoryName = $("#detail_category_dialog .categoryName").val();
		for (var j = 0; j < materials.length; j++) {
			checkedRequired.push($(materials[j]).find(".checkedRequired:checked").val());
			templateName.push($(materials[j]).find("#templateName").val());
			if ($(materials[j]).attr("templateId") == null) {
				templateId.push(0);
			} else {
				templateId.push($(materials[j]).attr("templateId"));
			}
		}
		if (materials.length == 0) {
			checkedRequired = 0;
			templateName = "";
			templateId = 0;
		}
		base.fnAjax({
			action: "updateMaterialTemplate.json",
			oData: {
				checkedRequired: checkedRequired,
				templateName: templateName,
				templateId: templateId,
				bulkstockCategoryId: bulkstockCategoryId,
				categoryName: categoryName
			},
			fnSuccess: function(data) {
				if (data.status == 200) {
					base.openUrl("commodityCategory.html");
					dialog.hideDialog($("#detail_category_dialog"));
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};

	//新增大宗商品类别
	var createBulkstockCategory = function() {
		var templateName = [];
		var categoryName = $("#add_category_dialog .categoryName").val();
		var checkedRequired = [];
		var templateId = [];
		var isFactoring = $("#add_category_dialog select[name=isFactoring]").val();
		var materials = $(".materials");
		for (var j = 0; j < materials.length; j++) {
			checkedRequired.push($(materials[j]).find(".checkedRequired:checked").val());
			templateName.push($(materials[j]).find("#templateName").val());
			if ($(materials[j]).attr("templateId") == null) {
				templateId.push(0);
			} else {
				templateId.push($(materials[j]).attr("templateId"));
			}
		}
		if (materials.length == 0) {
			checkedRequired = 0;
			templateName = "";
			templateId = 0;
		}
		base.fnAjax({
			action: "createBulkstockCategory.json",
			oData: {
				checkedRequired: checkedRequired,
				templateName: templateName,
				templateId: templateId,
				categoryName: categoryName,
				isFactoring: isFactoring
			},
			fnSuccess: function(data) {
				if (data.status == 200) {
					base.openUrl("commodityCategory.html");
					dialog.hideDialog($("#detail_category_dialog"));
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};

	// 获取模板明细
	var inquireMaterialTemplateDetail = function(commodityCategoryId) {
		base.fnAjax({
			action: "inquireMaterialTemplateDetail.json",
			oData: {
				commodityCategoryId: commodityCategoryId
			}, //传参
			fnSuccess: function(data) {
				if (data.status == 200) {
					$("#templateName").val(data.datas[0].templateName);
					$("#checkedRequired").doc(data.datas[0].checkedRequired);
				} else {
					base.alert(2, data.message);
				}
			}

		});
	};

	//商品融资材料模板明细
	var inquireCommodityCategoryDetail = function(commodityCategoryId) {
		base.fnAjax({
			action: "inquireBulkstockCategoryDetail.json",
			oData: {
				bulkstockCategoryId: commodityCategoryId
			}, //传参
			fnSuccess: function(data) {
				if (data.status == 200) {
					var tpl = $("#templateListTpl").html();
					var html = juicer(tpl, data);
					$("#templateListBody").html(html);
					
					$("#detail_category_dialog select[name=isFactoring]").val($("#detail_category_dialog select[name=isFactoring]").attr("val"));
				} else {
					base.alert(2, data.message);
				}
			}

		});
	};

	// 删除
	var deletead = function(commodityCategoryIds) {
		var delete_category_dialog = $("#delete_category_dialog");
		dialog.showDialog(delete_category_dialog, function() {});
		$(".footerBtn").on("click", "#sure_delete", function() {
			base.fnAjax({
				action: "disableBulkstockCategory.json", //接口名称
				oData: {
					bulkstockCategoryId: commodityCategoryIds
				}, //传递参数
				fnSuccess: function(data) { //成功回调
					if (data.status == 200) {
						inquireCommodityCategoryList();
					} else {
						base.alert(3, data.message);
					}
					dialog.hideDialog($("#delete_category_dialog"));
				}
			});
		});
	};

	// 同步商品类别
	var syncBulkstockCategory = function() {
		base.fnAjax({
			action: "syncBulkstockCategory.json", //接口名称
			oData: {}, //传递参数
			fnSuccess: function(data) { //成功回调
				if (data.status == 200) {
					base.alert(1, "同步成功！");
					location.href = "../commodityCategoryManage/commodityCategory.html"
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};

	// 同步商品类别-单条数据
	var syncBulkstockInfo = function(bulkstockCategoryId) {
		base.fnAjax({
			action: "syncBulkstockInfo.json", //接口名称
			oData: {
				bulkstockCategoryId: bulkstockCategoryId
			}, //传递参数
			fnSuccess: function(data) { //成功回调
				if (data.status == 200) {
					base.alert(1, "同步成功！");
					location.href = "../commodityCategoryManage/commodityCategory.html"
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};

// 停用商品类别-单条数据
	var deprecatedBulkstockCategory = function(bulkstockCategoryId) {
		base.fnAjax({
			action: "deprecatedBulkstockCategory.json", //接口名称
			oData: {
				bulkstockCategoryId: bulkstockCategoryId
			}, //传递参数
			fnSuccess: function(data) { //成功回调
				if (data.status == 200) {
					base.alert(1, "停用成功！");
					location.href = "../commodityCategoryManage/commodityCategory.html"
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};
	
	// 同步商品类别-单条数据
	var activeBulkstockCategory = function(bulkstockCategoryId) {
		base.fnAjax({
			action: "activeBulkstockCategory.json", //接口名称
			oData: {
				bulkstockCategoryId: bulkstockCategoryId
			}, //传递参数
			fnSuccess: function(data) { //成功回调
				if (data.status == 200) {
					base.alert(1, "启用成功！");
					location.href = "../commodityCategoryManage/commodityCategory.html"
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};

	//查询列表
	var inquireCommodityCategoryList = function() {
		var categoryName = $("#categoryName").val();
		var beginUpdateDate = $("#beginUpdateDate").val();
		var endUpdateDate = $("#endUpdateDate").val();
		base.fnAjax({
			action: "inquireBulkstockCategoryPageList.json",
			async: false, //同步异步
			nocode: false, //是否要登陆，true为不用登陆
			oData: {
				pageIndex: pageIndex,
				pageSize: pageSize,
				categoryName: categoryName,
				beginUpdateDate: beginUpdateDate,
				endUpdateDate: endUpdateDate
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					var tpl = $("#commodityCategoryTpl").html();
					var html = juicer(tpl, data);
					$("#commodityCategoryBody").html(html);

					$(".table_async_link").unbind("click").click(function() {
						var $this = $(this);
						dialog.showConfirmDialog("同步商品类别", "是否确定同步" + $this.parents("tr").attr("commoditycategoryname") + "?", function() {
							syncBulkstockInfo($this.parents("tr").attr("commodityCategoryId"));
						});
					});
					
					$(".table_active_link").unbind("click").click(function() {
						var $this = $(this);
						dialog.showConfirmDialog("启用商品类别", "是否确定启用" + $this.parents("tr").attr("commoditycategoryname") + "?", function() {
							activeBulkstockCategory($this.parents("tr").attr("commodityCategoryId"));
						});
					});
					
					$(".table_deprecated_link").unbind("click").click(function() {
						var $this = $(this);
						dialog.showConfirmDialog("停用商品类别", "是否确定停用" + $this.parents("tr").attr("commoditycategoryname") + "?", function() {
							deprecatedBulkstockCategory($this.parents("tr").attr("commodityCategoryId"));
						});
					});

					totalPageCount = data.totalPageCount;
					totalRecordCount = data.totalRecordCount;
					base.pageControl($("#newscategorypagenation"),
						totalRecordCount,
						data.pageIndex,
						data.pageSize,
						function(p) {
							pageIndex = p;
							inquireCommodityCategoryList();
						});
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	};

	// 获取商品类别
	var inquireCommodityCategoryPageList = function() {
		var html = function(data) {
			var str = "";
			for (var i = 0; i < data.datas.length; i++) {
				var row = data.datas[i];
				str += '<option value="' + row.commodityCategoryId + '">' + row.categoryName + '</option>';
			}
			$("#commodityCategoryName").append(str);
			if (commodityCategoryIdDic.enabled == 1) {
				$("#commodityCategoryName").val(commodityCategoryIdDic.commodityCategoryId);
			} else {
				commodityCategoryIdDic.enabled = 1;
			};
		};
		base.fnAjax({
			action: "inquireBulkstockCategoryPageList.json", //接口名称
			oData: {
				keyword: "",
				pageIndex: pageIndex,
				pageSize: pageSize
			}, //传递参数
			fnSuccess: function(data) { //成功回调
				if (data.status == 200) {
					html(data);
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};


	//继续添加材料模板
	var addMaterials = function() {
		var str = [
			'  <div style="margin-top: 16px;" class="materials">',
			'  <div style="display: inline-block">',
			'    <label for="" class="newsTitle">新增所需材料', , '：</label>',
			'    <input class="material" type="text" id="templateName" placeholder="例如：商品质检证明" />',
			'  </div>',
			'  <form style="display: inline-block">',
			'    <label for="" class="isUpload">是否必须上传：</label>',
			'	 <input type="radio" class="checkedRequired" name="checkedRequired" value="1" style="width: auto; height: auto;" />是',
			'    <input type="radio" class="checkedRequired" name="checkedRequired" value="0" checked="checked" style="width: auto; height: auto; margin-left: 20px;" />否',
			'    <span class="table_bar">| </span>',
			'    <span class="delete">删除 </span>',
			'  </form>',
			'  </div>',
		].join("");
		i++;
		$('.hr').before(str);
	};

	// 判断搜索框是否都为空
	var ifblank = function() {
		if (($("#categoryName")).val() == "") {
			$("#commodityCategoryId").val("");
		}
	};

	return {
		init: init
	};
});